package com.huaweicloud.servicestage.plugin;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.iam.v3.IamClient;
import com.huaweicloud.sdk.iam.v3.model.KeystoneListProjectsRequest;
import com.huaweicloud.sdk.iam.v3.model.KeystoneListProjectsResponse;
import com.huaweicloud.sdk.iam.v3.model.ProjectResult;
import com.huaweicloud.servicestage.command.CommandInit;

public class IamProject {
    public static String qureyProjectId(CommandInit commandInit, String region) {
        String endpoint = "https://iam." + region + ".myhuaweicloud.com";
        // 配置客户端属性
        HttpConfig config = HttpConfig.getDefaultHttpConfig();
        config.withIgnoreSSLVerification(true);

        // 创建认证
        BasicCredentials auth = new BasicCredentials()
            .withAk(commandInit.getAccessKey())
            .withSk(commandInit.getSecretKey());

        IamClient iamClient = IamClient.newBuilder()
            .withHttpConfig(config)
            .withCredential(auth)
            .withEndpoint(endpoint)
            .build();

        KeystoneListProjectsRequest request = new KeystoneListProjectsRequest();
        KeystoneListProjectsResponse response = iamClient.keystoneListProjects(request);
        return response.getProjects().stream().filter(v -> v.getName().equals(region)).map(ProjectResult::getId).findFirst()
            .orElse(null);

    }
}
